﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using WebService.Nafania.ViewLayer.Model.Base;
using WebService.Nafania.ViewLayer.Model.ObjectView;

namespace UI.Nafania.Helpers
{
	public static class ObjectViewExtention
	{
		public static MvcHtmlString ToView<TModel>(this HtmlHelper<TModel> html, TemplateView template)
		{
			var result = html.ToValueView(template);

			if (template.Data is HiddenView)
				return result;

			TagBuilder tb = new TagBuilder("fieldset")
			                	{
			                		InnerHtml = new TagBuilder("legend")
			                		            	{
			                		            		InnerHtml = template.Name
			                		            	}.ToString()
			                	};
			tb.InnerHtml += result.ToHtmlString();

			return MvcHtmlString.Create(tb.ToString());
		}

		internal static MvcHtmlString ToValueView<TModel>(this HtmlHelper<TModel> html, TemplateView template)
		{
			MvcHtmlString result = MvcHtmlString.Empty;
			if (template.Data is HiddenView)
			{
				var view = (HiddenView) template.Data;
				result = html.Hidden(template.Name, view.Value);
			}
			else if (template.Data is ListView)
			{
				var view = (ListView) template.Data;
				result = html.DropDownList(template.Name,
				                           view.Values.Select(x => new SelectListItem { Value = x.Key.ToString(), Text = x.Value.ToString(), Selected = x.Key.ToString() == view.Value.ToString()}));
			}
			else if (template.Data is TextView)
			{
				var view = (TextView) template.Data;
				result = html.TextBox(template.Name, view.Value);
			}
			else if (template.Data is ListTextView)
			{
				var view = (ListTextView) template.Data;
				for (int i = 0; i < view.Values.Length; i++)
				{
					var val = view.Values[i];
					result =
						MvcHtmlString.Create(result 
							+ (result != MvcHtmlString.Empty ? "<br />" : string.Empty) 
							+ html.TextBox(template.Name + i, val.Value, new { index = i }));
				}

				var addLink = new TagBuilder("a")
				              	{
				              		InnerHtml = "Add " + template.Name,
				              	};

				addLink.MergeAttributes(new Dictionary<string, string>
				                        	{
																		{ "href", "#" },
																		{ "action", "add-to-text-list"}
				                        	});

				result =
						MvcHtmlString.Create(result
							+ (result != MvcHtmlString.Empty ? "<br />" : string.Empty)
							+ addLink);
			}
			else
			{
				throw new NotImplementedException();
			}

			return result;
		}

	}
}